<?php

namespace app\api\controller;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Env;
use think\Request;
use app\api\model\Goods as GoodsModel;
use app\api\validate\GoodsValidate;
use think\Db;

class Goods extends Common
{
    /**
     *   商品列表
     * @param Request $request
     * @param GoodsModel $model
     * @return Json
     * @throws DbException
     */
    public function index(Request $request, GoodsModel $model)
    {
        $list = $model->getList($request->post(), $request->post('page'));
        if (!empty($list)) {
            return $this->returnJson(200, '成功', $list);
        } else {
            return $this->returnJson(404, '失败', $list);
        }
    }

    /**
     * 商品新增
     * @param Request $request
     * @param GoodsModel $model
     * @return \think\response\Json
     */
    public function add(Request $request, GoodsModel $model)
    {
        $data = $request->param();
        $spe = [];
        $data['create_time'] = time();
        $validate = new GoodsValidate();
        if (!$validate->check($data)) {
            return json(['code' => 500, 'msg' => $validate->getError()]);
        }
//        $data['color'] = json_decode($data['color'], true);
//        $data['size'] = json_decode($data['size'], true);
        // 不传款式，则只处理颜色和尺寸
        if ($request->has('style')) {
//            $data['style'] = json_decode($data['style'], true);
            // 处理 多个规格的混合组合
            foreach ($data['color'] as $key => $val) {
                foreach ($data['size'] as $key1 => $val1) {
                    foreach ($data['style'] as $key2 => $val2) {
                        $spe[] = [
                            'color' => $data['color'][$key],
                            'size' => $data['size'][$key1],
                            'style' => $data['style'][$key2]
                        ];
                    }
                }
            }
            foreach ($spe as $k => $v) {
                $data['color'] = $v['color'];
                $data['size'] = $v['size'];
                $data['style'] = $v['style'];
                $arr[] = $model::create($data)->id;
            }
        } else {
            foreach ($data['color'] as $key => $val) {
                foreach ($data['size'] as $key1 => $val1) {
                    $spe[] = ['color' => $data['color'][$key], 'size' => $data['size'][$key1],];
                }
            }
            foreach ($spe as $k => $v) {
                $data['color'] = $v['color'];
                $data['size'] = $v['size'];
                $arr[] = $model::create($data)->id;
            }
        }
//        $arr = $model->getGoodsAdd($data, $spe);
        if (!empty($arr)) {
            return json(['code' => 200, 'msg' => '添加成功', 'data' => $arr]);
        } else {
            return json(['code' => 404, 'msg' => '添加失败']);
        }
    }

    /**
     * 商品修改
     * @param $id
     * @param GoodsModel $model
     * @param Request $request
     * @return \think\response\Json
     */
    public function edit($id, GoodsModel $model, Request $request)
    {

        $data = $request->only($model->getFieldArray(false));
        $validate = new GoodsValidate();
        if (!$validate->check($data)) {
            return json(['code' => 404, 'msg' => $validate->getError()]);
        }
        $arr = $model->getGoodsEdit($id, $data);
        if (!empty($arr)) {
            return json(['code' => 200, 'msg' => '修改成功']);
        } else {
            return json(['code' => 404, 'msg' => '修改失败', 'data' => $arr]);
        }
        $id = request()->param('id');
        $current = $model->getInfo($id);
        $list = $model->getCate();
        if (!empty($list)) {
            return json(['code' => 200, 'msg' => '成功', 'list' => $list, 'current' => $current]);
        } else {
            return json(['code' => 200, 'msg' => '失败', 'data' => $list]);
        }
    }

    /**
     * 商品删除
     * int $id 商品id
     * @param $id
     * @param GoodsModel $model
     * @return Json
     */
    public function del($id, GoodsModel $model)
    {
        $list = $model->getGoodsDel($id);
        if ($list) {
            return json(['code' => 200, 'msg' => '成功', 'data' => $list]);
        } else {
            return json(['code' => 404, 'msg' => '商品已入库,无法删除']);
        }
    }

    /**
     * @param $id
     * @param GoodsModel $model
     * @return array|\PDOStatement|string|\think\Model
     */
    public function show($id, GoodsModel $model)
    {
        return $model->getInfo($id);
    }

    //上传图片

    /**
     * @param $id
     * @param Request $request
     * @param GoodsModel $goodsModel
     * @return \think\response\Json
     */
    public function upload($id, Request $request, GoodsModel $goodsModel)
    {
        try {
            $goods = $goodsModel->findOrFail($id);
        } catch (DataNotFoundException $e) {
            return json(['code' => 404, 'msg' => $e->getMessage()], 404);
        } catch (ModelNotFoundException $e) {
            return json(['code' => 404, 'msg' => $e->getMessage()], 404);
        } catch (DbException $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()], 500);
        }
        // 获取表单上传文件
        $files = $request->file('images');
        if (!$files) {
            return json(['code' => 404, 'msg' => '请选择上传的文件']);
        } else {
            // 建立目录
            $dir = '/public/upload/images/';
            $savePath = Env::get('root_path') . $dir;
            if (!is_dir($savePath)) {
                mkdir($savePath, 0777, true);
            }
            // 处理多图上传
            // 多于九个不能上传
            if (count($files) > 9) {
                return json(['code' => 404, 'msg' => '上传的文件不能超过九个']);
            }
            foreach ($files as $k => $file) {
                // 验证文件格式和大小
                // 移动到框架应用根目录/public/upload/images/ 目录下
                $info = $file->validate(['size' => 4194304, 'ext' => 'jpg,png,gif'])->move($savePath);
                if ($info) {
                    // 成功上传后 获取上传信息
                    $filename = $info->getSaveName();
                    $filepath = $dir . $filename;
                    $images[$k] = $filepath;
                } else {
                    // 上传失败获取错误信息
                    return json(['code' => 404, 'msg' => $file->getError()], 404);
                }
            }
            // 存储信息
            $goods->images = json_encode($images);
            if ($goods->save()) {
                return json(['code' => 200, 'msg' => '成功', 'current' => $goods->id]);
            } else {
                return json(['code' => 500, 'msg' => '失败']);
            }
        }
    }
}
